<template>
  <div>
    <div class="flex-between">
      <div class="flex">
        <div
          @click="changeBtn(1)"
          class="moban_btn"
          :class="active_btn == 1 ? 'moban_btn_active' : ''"
        >
          电脑模板
        </div>
        <div
          @click="changeBtn(2)"
          class="moban_btn"
          :class="active_btn == 2 ? 'moban_btn_active' : ''"
        >
          手机模板
        </div>
        <div class="search_box">
            <el-input placeholder="输入搜索关键词" v-model="templateName" class="input-with-select">
            <el-button @click="seach_confrim" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>

      </div>
      <div class="flex">
        <el-button
          class="home_btn"
          type="primary"
          style="margin-bottom: 30px; margin-right: 40px"
          @click="addMoban"
          >导入模板</el-button
        >
        <el-button
          class="home_btn"
          style="margin-bottom: 30px"
          @click="addMoban"
          >创建模板</el-button
        >
      </div>
    </div>

    <div v-if="active_btn == 1">
      <div class="moban_list_box flex-wrap flex">
        <div
          class="moban_item moban_item_pc"
          v-for="(item, i) of WebtemplateData"
          :key="i"
        >
          <img class="moban_img" :src="item.templateImg" alt="" />
          <div class="mobi_template_use_wrap">{{ item.views }}最近使用</div>
          <div class="mobi_template_image--mask">
            <!-- <img src="../../assets/iconfont/del.png" class="del_icon_moban" alt=""> -->
            <i
              class="el-icon-delete del_icon_moban"
              @click="delmoban(item)"
            ></i>
               <i
              class="el-icon-edit edit_icon_moban"
              @click="editmoban(item)"
            ></i>
            <div class="moban_btns flex-center">
              <div class="use_btn" @click="webSite(item)">使用</div>
              <div class="preview" @click="previewMoban(item)">预览</div>
            </div>
          </div>
          <div class="moban_name">{{ item.templateName }}</div>
        </div>
      </div>
    </div>

    <div v-else>
      <div class="moban_list_box flex-wrap flex">
        <div class="moban_item2" v-for="(item, i) of PhonetemplateData" :key="i">
          <img class="moban_img" :src="item.templateImg" alt="" />
          <div class="mobi_template_use_wrap">
            {{ (Math.random() * 20000).toFixed(0) }}最近使用
          </div>
          <div class="mobi_template_image--mask">
            <i
              class="el-icon-delete del_icon_moban"
              @click="delmoban(item)"
            ></i>
            <div class="moban_btns flex-center">
              <div class="use_btn" @click="phoneSite(item)">使用</div>
              <div class="preview" @click="previewMoban(item)">预览</div>
            </div>
          </div>
          <div class="moban_name">{{ item.templateName }}</div>
        </div>
      </div>
    </div>
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      title="新建模板"
      :visible.sync="TemplateDialog"
      width="40%"
    >
      <SetTemplate  @closeTK="closeTK" v-if="TemplateDialog"></SetTemplate>
    </el-dialog>

        <el-dialog
      append-to-body
      :close-on-click-modal="false"
      title="编辑模板"
      :visible.sync="editTemplateDialog"
      width="40%"
    >
      <SetTemplate :TemplateData="TemplateData"  @closeTK="closeTK" v-if="editTemplateDialog"></SetTemplate>
    </el-dialog>
  </div>
</template>

<script>
import SetTemplate from "./SetTemplate.vue";
import api from "@/api/models/api.js";
import { Alert } from "element-ui";
export default {
  components: { SetTemplate },
  props: ["pagination"],
  data() {
    return {
      active_btn: 1,
      TemplateDialog: false,
      editTemplateDialog: false,
      templateName:'',
      TemplateData:{},
      WebtemplateData: [],
      PhonetemplateData: [],
      total:null,
    };
  },
  created() {
    this.init(1);
  },
  watch:{
   pagination: {
         handler: function(value) {
            //do something
            this.init(this.active_btn)
         },
         deep: true
     }
  },
  methods: {
    editmoban(item){
      this.TemplateData=item
      if (item.isPassword == 1) {
        //需要密码
        this.$prompt("请输入密码", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(({ value }) => {
            api
              .templatePasswordVerification({ id: item.id, password: value })
              .then(async (res) => {
                if (res.code == 200) {
                   this.editTemplateDialog = true;
                } else {
                  this.$message.error(res.msg || res.message);
                }
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });
      }else{
         this.editTemplateDialog = true;
      }

    },
    addMoban() {
      this.TemplateDialog = true;
    },
    changeBtn(i) {
      this.active_btn = i;
      this.pagination.current=1
      this.init(i);
      this.$emit("getTotal", {active:i,total:this.total})
    },
    seach_confrim(){
       this.pagination.current=1
       api.getTemplateList({ type: this.active_btn,...this.pagination,templateName:this.templateName
       }).then((res) => {
         if(this.active_btn==1){
            this.WebtemplateData = res.data.records;
            this.total = res.data.total;
           }else{
            this.PhonetemplateData = res.data.records;
            this.total = res.data.total;
          }
          this.$emit("getTotal", {active:this.active_btn,total:res.data.total});
        });
    },
    async gophone(item) {
        let GlobalcanvasData = [];
         let canvasData =[];
        if (item.globalCanvaData && item.globalCanvaData.length) {
            GlobalcanvasData = await this.getJSON(item.globalCanvaData);
        }
        if(item.canvasData=="[]"||!item.canvasData){
            canvasData = []
        }else{
            canvasData = await this.getJSON(item.canvasData);
        }

        if(GlobalcanvasData.length){
          localStorage.setItem("canvasData", JSON.stringify(GlobalcanvasData[0].canvasData ? GlobalcanvasData[0].canvasData : []));
        localStorage.setItem("GlobalcanvasData",JSON.stringify(GlobalcanvasData?GlobalcanvasData:[]));
        localStorage.setItem("templateName", item.templateName);
        localStorage.setItem("templateNameId", item.id);
        this.$store.commit("setComponentData", GlobalcanvasData[0].canvasData);
        this.$store.commit("setCanvasStyle", GlobalcanvasData[0].canvasStyle);
        localStorage.setItem(
          "canvasStyle",
            JSON.stringify(GlobalcanvasData[0].canvasStyle)
        );
          this.$router.push(`/phoneSite?id=${item.id}&type=${item.type}&name=${item.templateName}`);
        }else{
          localStorage.setItem("canvasData", JSON.stringify([]));
        localStorage.setItem("GlobalcanvasData",JSON.stringify([]));
        localStorage.setItem("templateName", item.templateName);
        localStorage.setItem("templateNameId", item.id);
        this.$store.commit("setComponentData", []);
        this.$store.commit("setCanvasStyle", {
          width:375,
            height:812,
            scale:100
          });
        localStorage.setItem(
          "canvasStyle",
            JSON.stringify({
              width:375,
            height:812,
            scale:100
          })
        );
          this.$router.push(`/phoneSite?id=${item.id}&type=${item.type}&name=${item.templateName}`);
        }
        
        this.$emit("closeTK");
    },
    async goweb(item) {
        let GlobalcanvasData = [];
        let canvasData =[];
        if (item.globalCanvaData && item.globalCanvaData.length) {
            GlobalcanvasData = await this.getJSON(item.globalCanvaData);
        }else{
          GlobalcanvasData=[]
        }
        if(item.canvasData=="[]"||!item.canvasData){
            canvasData = []
        }else{
            canvasData = await this.getJSON(item.canvasData);
        }

        if(GlobalcanvasData.length){
             localStorage.setItem("canvasData", JSON.stringify(GlobalcanvasData[0].canvasData?GlobalcanvasData[0].canvasData:[]));
        localStorage.setItem(
          "GlobalcanvasData",
          JSON.stringify(GlobalcanvasData)
        );
        localStorage.setItem("templateName", item.templateName);
        localStorage.setItem("templateNameId", item.id);
        this.$store.commit("setComponentData", GlobalcanvasData[0].canvasData);
        localStorage.setItem("templateNameId", item.id);
        this.$store.commit("setCanvasStyle", GlobalcanvasData[0].canvasStyle);
        localStorage.setItem(
          "canvasStyle",
          JSON.stringify(GlobalcanvasData[0].canvasStyle)
        );
        }else{
           localStorage.setItem("canvasData", JSON.stringify([]));
          localStorage.setItem(
            "GlobalcanvasData",
            JSON.stringify(GlobalcanvasData)
          );
          localStorage.setItem("templateName", item.templateName);
          localStorage.setItem("templateNameId", item.id);
          this.$store.commit("setComponentData", []);
          localStorage.setItem("templateNameId", item.id);
          this.$store.commit("setCanvasStyle",{
            width:1920,
            height:1080,
            scale:100
          });
          localStorage.setItem(
            "canvasStyle",
            JSON.stringify({
            width:1920,
            height:1080,
            scale:100
          })
          );
        }
        this.$router.push(`/website?id=${item.id}&type=${item.type}&name=${item.templateName}`);
        this.closeTK()
    },
    async webSite(item) {
      if (item.isPassword == 1) {
        //需要密码
        this.$prompt("请输入密码", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(({ value }) => {
            api
              .templatePasswordVerification({ id: item.id, password: value })
              .then(async (res) => {
                if (res.code == 200) {
                  this.goweb(item);
                } else {
                  this.$message.error(res.msg || res.message);
                }
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });
      } else {
        this.goweb(item);
      }
    },
    async phoneSite(item) {
      if (item.isPassword == 1) {
        //需要密码
        this.$prompt("请输入密码", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(({ value }) => {
            api
              .templatePasswordVerification({ id: item.id, password: value })
              .then(async (res) => {
                if (res.code == 200) {
                  this.gophone(item);
                } else {
                  this.$message.error(res.msg || res.message);
                }
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });
      } else {
        this.gophone(item);
      }
    },
    delmoban(item) {
      this.$confirm("此操作将永久删除该模板, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          if (item.isPassword == 1) {
            this.$prompt("请输入密码", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
            }).then(({ value }) => {
              api
                .templatePasswordVerification({ id: item.id, password: value })
                .then(async (res) => {
                  if (res.code == 200) {
                    api.deleteTemplate({ id: item.id }).then((res) => {
                      this.$message.success(res.msg || res.message);
                      this.init(this.active_btn);
                    });
                  } else {
                    this.$message.error(res.msg || res.message);
                  }
                });
            });
          } else {
            api.deleteTemplate({ id: item.id }).then((res) => {
              this.$message.success(res.msg || res.message);
              this.init(this.active_btn);
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async getJSON(url) {
      return new Promise((resolve, reject) => {
        $.get(url, function (data) {
          resolve(data);
          return;
        });
      });
    },
    init(i) {
      // axios.post("http://api.hweihong.top/getGlobaleCanvasData").then((res) => {
      //   this.templateData = res.data.records;
      // });
      if (i == 1) {
        api.getTemplateList({ type: i,...this.pagination}).then((res) => {
          this.WebtemplateData = res.data.records;
          this.$emit("getTotal",  {active:this.active_btn,total:res.data.total});
        });
      } else {
        api.getTemplateList({ type: 2 ,...this.pagination}).then((res) => {
          this.PhonetemplateData = res.data.records;
          this.$emit("getTotal",  {active:this.active_btn,total:res.data.total});
        });
      }
    },
    closeTK() {
      this.TemplateDialog = false;
      this.editTemplateDialog = false;
      this.init(this.active_btn);
    },
    async useMoban(item) {
      let GlobalcanvasData = [];

      if (item.isPassword == 1) {
        //需要密码
        this.$prompt("请输入密码", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(({ value }) => {
            api
              .templatePasswordVerification({ id: item.id, password: value })
              .then(async (res) => {
                if (res.code == 200) {
                  if (item.globalCanvaData && item.globalCanvaData.length) {
                    GlobalcanvasData = await this.getJSON(item.globalCanvaData);
                  }
                  console.log(item);
                  let canvasData = await this.getJSON(item.canvasData);
                  if (item.canvasData) {
                    localStorage.setItem(
                      "canvasData",
                      JSON.stringify(canvasData)
                    );
                    localStorage.setItem(
                      "GlobalcanvasData",
                      JSON.stringify(GlobalcanvasData)
                    );
                    localStorage.setItem("templateName", item.templateName);
                    localStorage.setItem("templateNameId", item.id);
                    this.$store.commit("setComponentData", canvasData);
                    this.$emit("closeTK");
                  }
                }
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });
      }
    },
   async previewMoban(item) {
          let GlobalcanvasData = [];
          if (item.globalCanvaData && item.globalCanvaData.length) {
            GlobalcanvasData = await this.getJSON(item.globalCanvaData);
          }
          if(item.canvasData=="[]"||!item.canvasData){
            canvasData = []
          }else{
            canvasData = await this.getJSON(item.canvasData);
          }
            let canvasData = await this.getJSON(item.canvasData);
            localStorage.setItem("canvasData", JSON.stringify(canvasData));
            localStorage.setItem(
              "GlobalcanvasData",
              JSON.stringify(GlobalcanvasData)
            );
            localStorage.setItem("templateName", item.templateName);
            localStorage.setItem("templateNameId", item.id);
            this.$store.commit("setComponentData", canvasData);
              if(item.type==1){
                 this.$store.commit("setCanvasStyle", {
                  width: 1920,
                  height: 1080,
                  scale: 100,
                });
                localStorage.setItem(
                  "canvasStyle",
                  JSON.stringify({ width: 375, height: 812, scale: 100 })
                );
              }else{
                this.$store.commit("setCanvasStyle", {
                  width: 375,
                  height: 812,
                  scale: 100,
                });
                localStorage.setItem(
                  "canvasStyle",
                  JSON.stringify({ width: 375, height: 812, scale: 100 })
                );
              }
              this.$store.commit("setEditMode", "preview");
              if(item.type==1){
                this.$router.push('/preview')
              }else{
                this.$router.push('/MobilePreview')
              }
    },
  },
};
</script>

<style lang="scss" scoped>
.webCont {
  width: 400px;
  min-width: 300px;
  border-radius: 6px;
  padding-top: 28px;
  padding-left: 34px;
  position: relative;
  box-sizing: border-box;
  cursor: pointer;
  transition: all 0.5s;
  transform: translateZ(0);
  height: 170px;
  background-image: url("https://jzas.faisys.com/image/v2/site_mbg.png?v=202104251316");
  background-color: #4f83f1;
  margin-right: 30px;
  background-position: -3326px -130px;
  background-position: -3755px 0;
  margin-right: 80px;
}
.phoneCont {
  width: 400px;
  min-width: 300px;
  border-radius: 6px;
  padding-top: 28px;
  padding-left: 34px;
  position: relative;
  box-sizing: border-box;
  cursor: pointer;
  transition: all 0.5s;
  transform: translateZ(0);
  height: 170px;
  background-image: url("https://jzas.faisys.com/image/v2/site_mbg_v2.png?v=202201210950");
  background-color: transparent;
  margin-right: 30px;
  background-position: -430px -450px;
  margin-left: 80px;
}

#icon_site,
#icon_mobi {
  width: 22px;
  height: 22px;
}
.fk_site_info_design_text {
  color: #fff;
  font-size: 20px;
}
.mobantit {
  margin-left: 10px;
}
.mobansubtit {
  color: #fff;
  margin-top: 20px;
}
.goseji {
  color: #3a6afa;
  opacity: 0.9;
  background: #fff;
  padding: 0;
  width: 100px;
  height: 30px;
  font-size: 14px;
  line-height: 30px;
  text-align: center;
  border-radius: 15px;
  margin-top: 20px;
}
.goseji_phone {
  color: #00bdcb;
}
.hovertop:hover {
  box-shadow: 0 0 15px 2px rgb(217 223 231 / 80%);
  transform: translateY(-5px) translateZ(0);
  -webkit-transform: translateY(-5px) translateZ(0);
}
.moban_list_box {
  margin-top: 30px;
}
.moban_item {
  position: relative;
  margin-right: 10px;
  margin-top: 20px;
  width: 225px;
  height: 424px;
  // background: url("https://jzas.faisys.com/image/index/icon-mobi.svg?v=202003041245")
  // no-repeat;
  transition: transform 0.3s ease;
  cursor: pointer;
  .moban_img {
    position: absolute;
    top: 6px;
    left: 6px;
    width: calc(100% - 12px);
    height: calc(100% - 32px);
    background-repeat: no-repeat;
    background-size: cover;
    background-position-x: center;
    border-radius: 8px;
    overflow: hidden;
  }
  .mobi_template_use_wrap {
    position: absolute;
    right: 0;
    bottom: 10px;
    z-index: 100;
    display: inline-block;
    padding: 5px 6px;
    color: #fff;
    background: linear-gradient(#fec95b, #fda957);
    text-align: center;
    font-size: 12px;
    border-top-left-radius: 8px;
    border-bottom-right-radius: 8px;
  }
}
.moban_item2 {
  position: relative;
  margin-right: 160px;
  margin-top: 20px;
  width: 225px;
  height: 424px;
  // background: url("https://jzas.faisys.com/image/index/icon-mobi.svg?v=202003041245")
  // no-repeat;
  transition: transform 0.3s ease;
  cursor: pointer;
  .moban_img {
    position: absolute;
    top: 6px;
    left: 6px;
    width: calc(100% - 12px);
    height: calc(100% - 32px);
    background-repeat: no-repeat;
    background-size: cover;
    background-position-x: center;
    border-radius: 8px;
    overflow: hidden;
  }
  .mobi_template_use_wrap {
    position: absolute;
    right: 0;
    bottom: 10px;
    z-index: 100;
    display: inline-block;
    padding: 5px 6px;
    color: #fff;
    background: linear-gradient(#fec95b, #fda957);
    text-align: center;
    font-size: 12px;
    border-top-left-radius: 8px;
    border-bottom-right-radius: 8px;
  }
}
.moban_item2:hover {
  transform: translateY(-10px);
}
.moban_item2:hover .mobi_template_image--mask {
  display: block;
}

.moban_item_pc {
  width: 341px;
  height: 255px;
}
.moban_item:hover {
  transform: translateY(-10px);
}
.moban_item:hover .mobi_template_image--mask {
  display: block;
}
.mobi_template_image--mask {
  position: absolute;
  top: 6px;
  left: 6px;
  z-index: 1;
  transition: 0.8s;
  width: calc(100% - 12px);
  height: calc(100% - 32px);
  border-radius: 8px;
  background-color: rgba(0, 0, 0, 0.7);
  display: none;
}
.moban_btns {
  color: #fff;
  position: absolute;
  bottom: 60px;
  width: 100%;
  .use_btn {
    width: 60px;
    height: 34px;
    line-height: 34px;
    color: #fff;
    text-align: center;
    font-size: 14px;
    border-radius: 18px;
    background-color: #3583fb;
    cursor: pointer;
    margin-right: 15px;
  }
  .preview {
    width: 60px;
    height: 34px;
    line-height: 34px;
    color: #fff;
    text-align: center;
    font-size: 14px;
    border-radius: 18px;
    margin-left: 15px;
    cursor: pointer;
    background-color: #fb5d46;
  }
}
.moban_name {
  position: absolute;
  width: 100%;
  text-align: center;
  bottom: -13px;
  color: #000;
  font-size: 14px;
  font-weight: bold;
}
.moban_btn {
  width: 120px;
  height: 40px;
  background: #fff;
  color: #000;
  border-radius: 3px;
  line-height: 40px;
  text-align: center;
  margin-right: 40px;
  cursor: pointer;
}

.moban_btn_active {
  width: 120px;
  height: 40px;
  background: #5780ea;
  color: #fff;
  border-radius: 3px;
  line-height: 40px;
  text-align: center;
  margin-right: 40px;
}
.moban_btn:hover {
  background: #5780ea;
  color: #fff;
}
.moban_btn_active:hover {
  background: #5780ea;
}
.home_btn {
  width: 120px;
  height: 40px;
  background: #5780ea;
  color: #fff;
}
.del_icon_moban {
  position: absolute;
  z-index: 9;
  top: 8px;
  right: 7px;
  width: 24px;
  font-size: 24px;
  color: #fff;
}
.edit_icon_moban {
  position: absolute;
  z-index: 9;
  top: 8px;
  right: 40px;
  width: 24px;
  font-size: 24px;
  color: #fff;
}
.edit_icon_moban:hover,.del_icon_moban:hover{
 color: #5780ea;
}
.search_box{
  line-height: 40px;
}
</style>
